<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/common_header :: common_header(~{::title},~{::link},~{})">
    <title>编辑商品</title>
    <link href="js/jquery-confirm/jquery-confirm.min.css" th:href="@{/js/jquery-confirm/jquery-confirm.min.css}" rel="stylesheet">

    <!-- 富文本编辑器 -->
    <link th:href="@{/js/summernote/summernote.css}" rel="stylesheet">
</head>
<body>
    <div class="container-fluid p-t-15">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <header class="card-header"><div class="card-title">编辑商品</div></header>
                    <div class="card-body">
                        <form class="form-horizontal" id="form" action="#" method="post" enctype="multipart/form-data" onsubmit="return false;">
                            <div class="form-group row">
                                <label class="col-sm-2 col-form-label">商品类目</label>
                                <div class="col-sm-10">
                                    <input type="hidden" name="cid" th:value="${item.cid}" class="cid">
                                    <input type="hidden" name="id" th:value="${item.id}" class="id">
                                    <button class="btn btn-label btn-primary goodsCat"><label><i class="mdi mdi-file-document-box-search"></i></label> 选择类目</button>
                                    <span class="badge badge-pill badge-secondary charin" th:text="${catVo.catCharinName}"></span>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="title" class="col-sm-2 col-form-label">商品标题</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="title" th:value="${item.title}" name="title" autocomplete="off" placeholder="请输入商品标题">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="sellPoint" class="col-sm-2 col-form-label">商品卖点</label>
                                <div class="col-sm-10">
                                    <textarea class="form-control" id="sellPoint" th:text="${item.sellPoint}" name="sellPoint" rows="3" autocomplete="off" placeholder="商品卖点"></textarea>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="price" class="col-sm-2 col-form-label" >商品价格</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="price" th:value="${item.price}" name="price" autocomplete="off" placeholder="请输入商品价格">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="price" class="col-sm-2 col-form-label" >库存数量</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="num" name="num" th:value="${item.num}" autocomplete="off" placeholder="请输入库存数量">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-2 col-form-label" >商品图片</label>
                                <div class="col-sm-10">
                                    <ul class="list-inline row lyear-uploads-pic mb-0">
                                        <li class="col-6 col-md-4 col-lg-2 base64Img" style="display: none" >
                                            <figure>
                                                <img th:src="${item.image}" src="" style="max-height: 200px;min-height: 85px" id="img" alt="商品主图">
                                                <figcaption>
                                                    <a class="btn btn-round btn-square btn-primary" href="#!" onclick="image()"><i class="mdi mdi-eye"></i></a>
                                                    <a class="btn btn-round btn-square btn-danger" href="#!"><i class="mdi mdi-delete"></i></a>
                                                </figcaption>
                                            </figure>
                                        </li>
                                        <li class="col-6 col-md-4 col-lg-2 ">
                                            <a class="pic-add" id="add-pic-btn" href="#!" title="点击上传"></a>
                                            <input type="file" value="" accept="image/*"  id="file" name="image" style="display: none">
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-2 col-form-label">商品状态</label>
                                <div class="form-check col-sm-10">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" th:checked="${item.status==1}" type="radio" name="status" id="status1" value="1">
                                        <label class="form-check-label" for="status1">正常</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" th:checked="${item.status==0}" type="radio" name="status"  value="0">
                                        <label class="form-check-label" >禁用</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" th:checked="${item.status==2}"  type="radio" name="status"  value="2">
                                        <label class="form-check-label" >上架</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" th:checked="${item.status==3}" type="radio" name="status" value="3">
                                        <label class="form-check-label" >下架</label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-2 col-form-label" >商品描述</label>
                                <div class="summernote">

                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-2 col-form-label" >商品规格</label>
                                <div class="form-check col-sm-10">
                                    <div class="paramData">

                                    </div>
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-sm-10">
                                    <button type="button" onclick="submitForm()" class="btn btn-primary">修改</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
        </div>
    </div>
</div>
<div th:replace="common/common_foot :: foot"></div>
<script type="text/javascript" src="js/jquery-confirm/jquery-confirm.min.js" th:src="@{/js/jquery-confirm/jquery-confirm.min.js}"></script>
<script type="text/javascript" th:src="@{/js/summernote/summernote.js}"></script>
<script type="text/javascript" th:src="@{/js/summernote/summernote-zh-CN.js}"></script>
<script type="text/javascript" th:src="@{/js/layer/layer.js}"></script>
<script type="text/javascript" th:inline="javascript">

    //商品描述
    var itemDesc = /*[[${item.itemDesc}]]*/;

    //商品规格
    var paramItem = /*[[${paramItem.paramData}]]*/;

    $("#add-pic-btn").click(function (){
        $("#file").click()
    })

    $("#file").change(function (){
        var data = new FormData();
        data.append("uploadFile",document.getElementById('file').files[0]);

        var l = $('body').lyearloading({
            opacity: 0.2,
            spinnerSize: 'lg'
        });

        uploadFile("/upload/pic/upload",data,function (res){
            //上传成功
            $("#img")[0].src = res.data
            $(".base64Img").show();
            l.destroy();
        })
    })

    //如果使用jQuery更改了值，jquery change()将不起作用
    $(".cid").change(function (){
        var cid = $(".cid").val()
        //类目选择改变了 触发
        $.get("/itemParam/getItemParam?cid="+cid,{},function (res){
            if (res.code === 500 ){
                alertTip("没有找到该商品的规格")
                return
            }
            createParam(JSON.parse(res.paramData));
        })
    })

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        var width = img.naturalWidth || img.width;
        var height = img.naturalHeight || img.height;
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height); // 绘制图像

        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); // 图片格式
        var dataURL = canvas.toDataURL("image/" + ext); // 包含图片展示的 data URI
        return dataURL;
    }

    function image(){
        $.confirm({
            title: '商品主图',
            boxWidth: '80%',
            useBootstrap: false,
            content: '<img width="100%" src="'+$("#img")[0].src+'">',
            animation: 'scale',
            animationClose: 'top',
            buttons: {
                '关闭': function() {}
            },
        });
    }

    function overwriteUpload(file,editor,$editable){
        var fileName = false;
        try{
            fileName = file['name']
        }catch (e){
            fileName = false
        }
        if (!fileName){
            $(".note-alarm").remove()
        }

        var data = new FormData();
        data.append("uploadFile",file);

        uploadFile("/upload/pic/upload",data,function (res){
            //上传成功
            $('.summernote').summernote('insertImage',res.data);
        })
    }

    function submitForm(){
        $('.summernote').summernote('code')
        var form = $("#form")[0];

        var data = new FormData(form);
        data.delete("files");
        data.delete("image");

        data.append("image",$("#img")[0].src);
        data.append("itemDesc",$('.summernote').summernote('code'));

        var paramData = getParam()
        data.append("paramData",JSON.stringify(paramData));

        var l = $('body').lyearloading({
            opacity: 0.6,
            backgroundColor: '#ffffff',
            imgUrl: '/images/loader.gif',
            spinnerText: '后台处理中，请稍后...',
            textColorClass: 'text-info'
        });

        $.ajax({
            data:data,
            type:"post",
            url:"/goods/updateGoods",
            cache:false,
            contentType:false,
            processData:false,
            success:function (res){
                l.destroy();
                if (res.code === 0){
                    //上传成功
                    alert("修改成功")
                }
                else{
                    alert(res.data)
                }
            },
            error:function (res){
                alert("上传失败")
            }
        })
    }

    /**
     * 创建商品规格
     * @param array
     */
    function createParam(array){
        $(".paramData").empty();
        var html = "";
        for (let i = 0; i < array.length; i++) {
            var groupHtml = "<div class='group'>"
            var endGroupHtml = "</div>"

            var obj = array[i]
            var group = obj.group;
            var params = obj.params

            var groupTag = `<div class="row">
                        <div class="alert alert-primary groupName" role="alert">${group}</div>
                    </div>`;

            var param = "";
            for (let j = 0; j < params.length; j++) {
                var pname = params[j]
                var item = {}
                if (pname.k==undefined){
                    item.k = pname
                    item.v = ""
                }
                else{
                    item.k = pname.k
                    item.v = pname.v
                }
                param += `
                    <div class="row form-group">
                        <label class="col-sm-2 col-form-label" style="background-color:#faf4fa" >${item.k}</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control"  name="param" value="${item.v}" autocomplete="off" placeholder="请输入规格">
                        </div>
                    </div>`;
            }
            html += groupHtml + groupTag + param + endGroupHtml
        }
        $(".paramData").append(html)
    }

    /**
     * 获取商品规格
     * @returns {*[]}
     */
    function getParam(){
        var paramArr = []
        $(".paramData .group").each(function (i,e){
            var paramObj = {}

            var groupName = $(e).find(".groupName").text()
            paramObj.group = groupName
            paramObj.params = []

            var g = $(e).find(".form-group")
            g.each(function (i,data){
                var param = {}
                var k = $(data).find("label").text()
                var v = $(data).find("input[name=param]").val()
                param.k = k
                param.v = v
                paramObj.params.push(param)
            })
            paramArr.push(paramObj)
        })
        console.log(paramArr)
        return paramArr
    }

    /**
     * 后续修改为layer
     */
    $(".goodsCat").click(function (res){
        layer.open({
            type: 2,
            title: '选择商品类目',
            shadeClose: true,
            shade: 0.5,
            area: ['500px', '70%'],
            btn: ['选择', '关闭'],
            yes: function(index, layero){
                var body = layer.getChildFrame('body',index);//建立父子联系【核心】
                var iframeWin = window[layero.find('iframe')[0]['name']];//【核心】
                var v = iframeWin.get();    //调用子页面的方法
                if (v == null){
                    layer.msg("请选择叶子节点")
                    return ;
                }
                var parse = JSON.parse(v);
                $(".charin").text(parse.catCharinName)
                $(".cid").val(parse.cid).change()
                layer.close(index)
                sessionStorage.removeItem("select")
            },
            content: '/goods/itemCat' //iframe的url
        });
    })
    $(document).ready(function () {
        $(".base64Img").show()
        $('.summernote').summernote({
            lang: 'zh-CN',
            height:400,
            minHeight:300,
            maxHeight:500,
            focus:true,
            callbacks:{
                onImageUpload: function (files,editor,$editable){
                    overwriteUpload(files[0],editor,$editable)
                }
            }
        });
        $('.summernote').summernote('code', itemDesc);
        createParam(JSON.parse(paramItem))
    });
</script>
</body>
</html>